using System;
using System.Collections.Generic;
using System.Text;
using GameFramework;
using GameFramework.Event;
using UnityEngine;
using UnityGameFramework.Runtime;

namespace StarForce
{
    /// <summary>
    /// http组件
    /// </summary>
    public class HttpComponent : GameFrameworkComponent
    {
        /// <summary>
        /// web Ip地址
        /// </summary>
        [SerializeField] private string m_IP = "127.0.0.1";

        /// <summary>
        /// web 端口号
        /// </summary>
        [SerializeField] private string m_Port = "3000";

        /// <summary>
        /// 签名
        /// </summary>
        private string m_Sign;

        private void Start()
        {
            GameEntry.Event.Subscribe(WebRequestSuccessEventArgs.EventId, OnWebRequestSuccess);
        }

        /// <summary>
        /// web回调成功事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnWebRequestSuccess(object sender, GameEventArgs e)
        {
            WebRequestSuccessEventArgs result = (WebRequestSuccessEventArgs) e;
            
            //todo 接受数据回调后进行数据分发
            GameEntry.Event.Fire(sender,ReferencePool.Acquire<WebResponseEventArgs>().Fill(result.UserData.ToString(),Utility.Converter.GetString(result.GetWebResponseBytes())));
        }

        /// <summary>
        /// Post方法 
        /// </summary>
        /// <param name="jsonMap">数据</param>
        /// <param name="urlNmae">Url名称</param>
        /// <returns></returns>
        public int Post(Dictionary<string, object> jsonMap, string urlName)
        {
            string url = GetWebPostUrl(urlName);
//
            string jsonData = JsonString(m_Sign, jsonMap);
//
            Log.Info("request-{0}:{1}", urlName, jsonData);
//
//            //加密
//            // jsonData = RSAEncryption(jsonData, false);
//            //
//            // jsonData = "{\"msg\":\"" + jsonData + "\"}";
//            // jsonData = Utility.Text.Format("{\"msg\":\" {0} \"}", jsonData);
//
            int webId = GameEntry.WebRequest.AddWebRequest(url, Encoding.UTF8.GetBytes(jsonData), urlName);
            return webId;
            //todo 可以添加加载中的界面
        }

        /// <summary>
        /// 获取Url
        /// </summary>
        /// <param name="urlName"></param>
        /// <returns></returns>
        public string GetWebPostUrl(string urlName)
        {
            string webUrl;
            if (!URL.WebUrl.TryGetValue(urlName, out webUrl))
            {
                throw new GameFrameworkException("non-existent url");
            }

            return Utility.Text.Format("http://{0}:{1}{2}", m_IP, m_Port, webUrl);
        }


        /// <summary>
        /// 转换为json字符串
        /// </summary>
        /// <param name="sign"></param>
        /// <param name="jsonMap"></param>
        /// <returns></returns>
        public string JsonString(string sign, Dictionary<string, object> jsonMap)
        {
            string str = "{\"";

            if (jsonMap != null)
            {
                foreach (KeyValuePair<string, object> keyValuePair in jsonMap)
                {
                    if (keyValuePair.Value == null)
                    {
                        Log.Error(keyValuePair.Key + ":null");
                    }
                    else
                    {
                        string key = keyValuePair.Key;
                        var va = keyValuePair.Value;

                        if (va is string)
                        {
                            str += key + "\": \"" + va + "\",\"";
                        }
                        else if (va is bool)
                        {
                            str += key + "\":" + va.ToString().ToLower() + ",\"";
                        }
                        else if (va is int || va is float || va is double || va is long)
                        {
                            str += key + "\": " + va + ",\"";
                        }
                        else if (va is List<string> list)
                        {
                            str += key + "\":[";
                            for (int i = 0; i < list.Count; i++)
                            {
                                str += "\"" + list[i] + "\",";
                            }

                            if (list.Count > 0)
                            {
                                str = str.Substring(0, str.Length - 1);
                            }

                            str += "],\"";
                        }
                        else
                        {
                            Log.Info(va.GetType());
                        }
                    }
                }

                int l = str.Length - 2;
                str = str.Substring(0, l);

                str += "}";
            }
            else
            {
                str = "{}";
            }

//            string temp = " {\"sign\": \"" + sign + "\",\"inmap\": " + str + ",\"inlist\": null}";
            string temp = str;
            return temp;
        }

        /// <summary>
        /// 订阅web回调事件
        /// </summary>
        /// <param name="urlName"></param>
        /// <param name="handler"></param>
        public void Subscribe(string urlName, EventHandler<GameEventArgs> handler)
        {
            GameEntry.Event.Subscribe(WebUtility.GetIntHash(urlName), handler);
        }
        
        /// <summary>
        /// 取消订阅web回调事件
        /// </summary>
        /// <param name="urlName"></param>
        /// <param name="handler"></param>
        public void UnSubscribe(string urlName, EventHandler<GameEventArgs> handler)
        {
            GameEntry.Event.Unsubscribe(WebUtility.GetIntHash(urlName), handler);
        }
    }
}